package cn.tudo.egweibo1.controller;

import cn.tudo.egweibo1.mapper.UserMapper;
import cn.tudo.egweibo1.pojo.dto.UserLoginDTO;
import cn.tudo.egweibo1.pojo.dto.UserRegDTO;
import cn.tudo.egweibo1.pojo.entity.User;
import cn.tudo.egweibo1.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    /**注册功能
     *
     * @param userRegDTO
     * @return
     */
    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return 1; //注册成功

    }

    /**
     * 2.登录功能
     */
    @PostMapping("login")
    public int login(@RequestBody UserRegDTO userRegDTO, HttpSession session) {
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO == null) {
            return 3;
        }
        if ((userRegDTO.getPassword().equals(userVO.getPassword()))) {
            session.setAttribute("user", userVO);
            return 1;

        }
        return 2;

    }
    /**
     * 3.获取当前用户功能
     */
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO=(UserVO) session.getAttribute("user");

        return userVO;
    }
    @GetMapping("logout")
    public void logout(HttpSession session){session.removeAttribute("user");}


}